package com.ganbo.pattern.proxy.dynamicproxy.cglib;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

class Person {

    public void sayHello(String name) {
        System.out.println(name + " say hello...");
    }
}


class CgLibHandler implements MethodInterceptor {

    private Object target;

    public CgLibHandler(Object target) {
        this.target = target;
    }

    public Object getInstance(Class targetClass) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetClass);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        long start = System.currentTimeMillis();
        System.out.println("准备开车");
        Object result = methodProxy.invokeSuper(o, objects);
        System.out.println("结束开车,营养跟不上了。开车时长:" + (System.currentTimeMillis() - start) + "毫秒。");
        return result;
    }
}

public class Test {

    public static void main(String[] args) {
        CgLibHandler cgLibHandler = new CgLibHandler(new Person());
        Person instance = (Person) cgLibHandler.getInstance(Person.class);
        instance.sayHello("admin");
    }

}
